﻿using NCP.Core;
using NCP.Core.DataUtil;
using NCP.Core.Exceptions;
using NCP.Core.IoC;
using NCP.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;

namespace NCP.Service
{
    public class GroupMissionService:IService
    {
        private SqlSugarClient _client;
        public GroupMissionService()
        {
            _client = DbHelper.GetSqlSugarClient();
        }

        public List<GroupMission> GetListForPage(Expressionable<GroupMission> whereExpression, PageModel page, string orderFields = "GpCode")
        {
            int count = 0;
            var result = _client.Queryable<GroupMission>().Where(whereExpression.ToExpression()).OrderBy(orderFields).ToPageList(page.PageIndex, page.PageSize, ref count);
            page.TotalCount = count;
            return result;
        }

        public List<GroupMission> GetAllList(Expressionable<GroupMission> whereExpression, string orderFields = "GpCode")
        {
            var result = _client.Queryable<GroupMission>().Where(whereExpression.ToExpression()).OrderBy(orderFields).ToList();
            return result;
        }

        public List<VGpinfo> GetGpListForPage(Expressionable<VGpinfo> whereExpression, PageModel page, string orderFields = "GpCode")
        {
            int count = 0;
            var result = _client.Queryable<VGpinfo>().Where(whereExpression.ToExpression()).OrderBy(orderFields).ToPageList(page.PageIndex, page.PageSize, ref count);
            page.TotalCount = count;
            return result;
        }

        public VGpinfo GetVGpinfo(Expressionable<VGpinfo> whereExpression)
        {
            return _client.Queryable<VGpinfo>().Where(whereExpression.ToExpression()).First();
        }

        public int SaveMission(List<GroupMission> items, string gpCode,string drugCode)
        {
            if (items == null)
                items = new List<GroupMission>();
            VGpinfo oldGpInfo = _client.Queryable<VGpinfo>().Where(x => x.GpCode == gpCode&&x.DrugCode==drugCode).First();
            MessageException.CheckNullException(oldGpInfo, "获取采集批次信息失败!" + gpCode);

            var oldItems = _client.Queryable<GroupMission>().Where(x => x.GpCode == gpCode &&x.DrugCode==drugCode).ToList();

            _client.BeginTran();
            try
            {
                #region 操作日志

                string oldCon = "";
                string newCon = "";
                //oldItems.ForEach(x => oldCon += $"{x.DrugCode},{x.TaskQTY.ToString("0.######")}^");
                items.ForEach(x => {
                    x.GpName = oldGpInfo.GpName;
                    x.ValidFlag = "1";
                });
                SysOperLogService.WriteSysOperLog(new SysOperLog
                {
                    EventType = "集采任务维护",
                    EventCon = "修改",
                    OldCon = oldCon.TrimEnd('^'),
                    NewCon = newCon.TrimEnd('^')
                });

                #endregion
                //删除信息
                List<string> delItems = new List<string>();
                foreach (var item in oldItems)
                {
                    if (!items.Exists(x => x.DeptCode == item.DeptCode))
                    {
                        delItems.Add(item.DeptCode);
                    }
                }
                if (delItems.Count > 0)
                {
                    _client.Deleteable<GroupMission>().Where(x => x.GpCode == gpCode && x.DrugCode==drugCode && delItems.Contains(x.DeptCode)).ExecuteCommand();
                }
                //保存信息
                var insertItems = new List<GroupMission>();
                var updateItems = new List<GroupMission>();
                foreach (var item in items)
                {
                    item.GpCode = gpCode;
                    item.OperCode = MemberUtil.CurrentMember.Code;
                    item.OperDate = DateTime.Now;
                    if (oldItems.Exists(x => x.DeptCode == item.DeptCode))
                    {
                        updateItems.Add(item);
                    }
                    else
                    {
                        insertItems.Add(item);
                    }
                }
                _client.Insertable(insertItems).ExecuteCommand();
                _client.Updateable(updateItems).WhereColumns(x => new { x.GpCode, x.DrugCode,x.DeptCode }).ExecuteCommand();

                _client.CommitTran();
            }
            catch
            {
                _client.RollbackTran();
                throw;
            }
            return 1;
        }

        //批量导入
        public int SaveMission(List<GroupMission> items)
        {
            _client.BeginTran();
            List<GroupMission> newitems = new List<GroupMission>();
            List<GroupMission> upitems = new List<GroupMission>();
            //删除批次任务
            _client.Deleteable<GroupMission>().Where(t => t.GpCode == items[0].GpCode).ExecuteCommand();
            foreach (var item in items)
            {
                
                VGpinfo gpInfo = _client.Queryable<VGpinfo>().Where(x => x.GpCode == item.GpCode && x.DrugCode == item.DrugCode).First();
                if (gpInfo == null)
                    continue;
                item.Unit = gpInfo.PackUnit;
                newitems.Add(item);
                //GroupMission existitem = _client.Queryable<GroupMission>().Where(t => t.GpCode == item.GpCode && t.DeptCode == item.DeptCode && t.DrugCode == item.DrugCode).First();
                //if (existitem!=null && existitem.ID>0)
                //{
                //    item.ID = existitem.ID;
                //    upitems.Add(item);
                //}
                //else
                //{
                //    newitems.Add(item);
                //}
            }
            try {
                _client.Insertable(newitems).ExecuteCommand();
                //_client.Updateable(upitems).WhereColumns(x => new { x.GpCode, x.DrugCode, x.DeptCode }).ExecuteCommand();

                _client.CommitTran();
            }
            catch
            {
                _client.RollbackTran();
                throw;
            }
            return 1;
        }

        public DataTable export(string gpcode,string drugCode)
        {
           
            var data = _client.Queryable<GroupMission>()
                .InnerJoin<PhaBaseInfo>((g, p) => g.DrugCode == p.DrugCode)
                .Where(Expressionable.Create<GroupMission>().AndIF(!string.IsNullOrEmpty(gpcode),g=>g.GpCode==gpcode)
                .AndIF(!string.IsNullOrEmpty(drugCode),g=>g.DrugCode==drugCode).ToExpression())
                .Select<dynamic>((g, p) => new
                {
                    集采编码 = g.GpCode,
                    集采名称 = g.GpName,
                    药品编码 = g.DrugCode,
                    药品名称 = p.DrugName,
                    药品规格 =  p.Specs,
                    科室编码 = g.DeptCode,
                    任务科室 = g.DeptName,
                    完成任务量 = g.Qyt,
                    完成比例 = g.Rate

                })
                .ToDataTable();

            return data;
        }
    }
}
